package com.dyh.quickdemo.demos.leqeeTool.db;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.List;

/*
@Author=Joey Wheeler
@Date=2020/10/16 13:52
*/
@Service
@Slf4j
public class DbQueryServiceIml implements DbQueryService{

    @Autowired
    RestTemplate restTemplate;


    @Override
    public void call(ReqUrl reqUrl) {
        int offset = 0;
        int size = 30;
        Req req = new Req ();
        BeanUtils.copyProperties(reqUrl,req);
        String sql = req.getSql();
        List<JSONObject> jos =new ArrayList<>();
        for (;;){
            /*limit 前有个空格*/
            req.setSql(sql+String.format(" limit %s,%s",offset,size));
            Rsp rsp = restTemplate.postForObject(reqUrl.getUrl(),req,Rsp.class);
            log.info("第{}页==============",offset/size+1);
            //log.info(JSON.toJSONString(rsp));
            jos.addAll(rsp.getData().getData());
            if (CollectionUtils.isEmpty(rsp.getData().getData())||
                rsp.getData().getData().size()<size
            )
                break;
            offset+=size;
        }


        log.info(JSON.toJSONString(jos));

    }

    @Override
    public void callRaw(ReqUrl reqUrl) {
        Req req = new Req ();
        BeanUtils.copyProperties(reqUrl,req);
        String res = restTemplate.postForObject(reqUrl.getUrl(),req,String.class);
        log.info(res);
    }
    /*
     String url = "https://databasehub.leqee.com/api/QuickQueryController/syncExecute";
        Req req = new Req();
        req.setDatabase_id(36);
        req.setSql("select * from fairjob.group order by group_id desc limit 500");
        req.setToken("b6cba3e6d69948981ef9075d21ed48e35f89069e44c8b");
        Rsp rsp = restTemplate.postForObject(url,req,Rsp.class);

        System.out.println();
    */
}
